package com.lancea12.buster.android;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.HashMap;

import javax.net.SocketFactory;

import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class ControllerEndpoint implements Runnable {

	private Socket endpoint;
	private OutputStream out;
	private InputStream in;
	private long requestID = 1;
	private boolean stop;
	private Handler mHandler;
	
	public ControllerEndpoint(Handler mHandler) {
		this.mHandler = mHandler;
	}
	
	@Override
	public void run() {
		stop =false;
		Log.d("Buster", "controller endpoint started");
		createSocket();
		
		// listen for any replies
        
		try {
			while(!stop){
				if(in != null && in.available() > 0){
					byte buf[] = new byte[in.available()];
					in.read(buf);

					Message mes = new Message();
					Bundle bun = new Bundle();
					bun.putString("response", new String(buf));
					mes.setData(bun);
					mHandler.sendMessage(mes);
				}
			}
			if(endpoint != null){
				endpoint.close();
			}
			Log.d("Buster", "closing controller socket");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void stopThread(){
		stop = true;
	}
	
	private void createSocket(){
        try {
			endpoint = SocketFactory.getDefault().createSocket(
				InetAddress.getByAddress(
					new byte[]{(byte)192, (byte)168, (byte)2, (byte)12}), 
					1221);
			out = endpoint.getOutputStream();
			in = endpoint.getInputStream();
			Log.d("Buster", "direct socket connected on port 1221");
			
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void sendRequest(HashMap<String, Object> request) {
		request.put("requestID", requestID);
		if(out == null){
			Log.d("Buster", "Socket not connected");
			return;
		}
		try {
			JSONObject jso = new JSONObject(request);
			out.write(jso.toString().getBytes());
			requestID++;
		} catch (IOException e) {
			e.printStackTrace();
		}

		//new Thread(new Sender(request)).start();
	}
	
	private class Sender implements Runnable{

		private HashMap<String, Object> request;
		
		public Sender(HashMap<String, Object> request){
			this.request = request;
		}
		
		
		@Override
		public void run() {
			try {
				JSONObject jso = new JSONObject(request);
				out.write(jso.toString().getBytes());
				requestID++;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}

}
